package jp.co.cos.ittrick.channel.controller.client;

import jp.co.cos.ittrick.channel.meta.TableModelMeta;
import jp.co.cos.ittrick.channel.model.PageModel;
import jp.co.cos.ittrick.channel.model.TableModel;
import jp.co.cos.ittrick.channel.service.PageService;
import jp.co.cos.ittrick.channel.service.TableService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;

public class InsertTableController extends Controller {

    private PageService pageService;
    private TableService tableService;

    public InsertTableController() {
        pageService = new PageService();
        tableService = new TableService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String page = asString("page");
        String name = asString("name");

        // 親の取得
        PageModel pageModel = pageService.getPageByKey(Integer.valueOf(page));

        // Modelの設定
        TableModel model = new TableModel();
        model.setName(name);
        model.getPageModelRef().setModel(pageModel);

        // Insert
        Key key = tableService.insert(model);

        model = tableService.getTableByKey((int)key.getId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(TableModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }

}
